<script setup lang="ts">
import { inject, onMounted, ref } from "vue";
import { storeToRefs } from "pinia";
import useConsultStore from "@/pinia/modules/consultStore.ts";
import type { Ref, ComputedRef } from "vue";
import type { Patient } from "@/types/patientTypes";
import PatientItem from "@/views/patient/components/patientList/patientItem.vue";


const emits = defineEmits<{
    (eventName: "getPatientId", patient: string): void
}>();

const consultStore = useConsultStore();

const { consultInfo } = storeToRefs(consultStore);

/*消费祖宗组件的数据*/
const patientList = inject<Ref<Patient[]>>("patientList");
const isSelect = inject<ComputedRef<boolean>>("isSelect");

/*选中的患者ID*/
const patientId = ref<string>("");

/*选择患者的回调函数*/
const selectPatient = (patient: string) => {
    patientId.value = patient;
    emits("getPatientId", patientId.value);
};

/*查找默认患者的回调函数*/
const findDefaultPatientId = () => {
    // 如果有患者ID则return
    if (patientId.value) return;
    // 如果不是选中患者模式则return
    if (!isSelect?.value) return;
    // 查找所有的患者列表中是否有和patientId相同的患者
    const defaultPatient = patientList?.value.find((patient: Patient) => patient.id === patientId.value);
    if (defaultPatient) {
        // 找到了
        patientId.value = defaultPatient.id as string;
    } else {
        // 没有找到,判断consultInfo.value.patientId是否有患者ID
        if (consultInfo.value.patientId) {
            // 找到了
            patientId.value = consultInfo.value.patientId;
        } else {
            // 没有找到(默认第一个患者为选中的患者)
            patientId.value = patientList?.value[0]?.id as string;
        }
    }

};

onMounted(() => {
    setTimeout(() => {
        findDefaultPatientId();
        emits("getPatientId", patientId.value);
    }, 500);
});


</script>

<template>
    <patient-item v-for="(patient) in patientList" :key="patient.id" :patient="patient" :patientId="patientId" @click="selectPatient"></patient-item>
</template>
